package com.lagou.registry;

import com.alibaba.fastjson.JSON;
import com.lagou.anno.MyRpcProvider;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

@Component
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix="server.provider")
public class ZkProviderRegistry extends ZkRegistry {

    private String ip;

    private int port;

    private String appName;

    @Override
    public String getPath() {
        return "/provider";
    }

    @Override
    @PostConstruct
    public void init() {
        System.out.println("获取配置文件中当前服务器信息ip:"+ip+",port:"+port);
        init(ip,port);
    }

    public void init(String ip,int port){
        Map<String, Object> beansWithAnnotation = ac.getBeansWithAnnotation(MyRpcProvider.class);
        if (beansWithAnnotation.size() > 0 ) {
            //当生产者数量大于0，才进行zk注册
            Set<Class> classSet = new HashSet<>();
            for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
                String key = entry.getKey();
                Class<?>[] interfaces = entry.getValue().getClass().getInterfaces();
                for (Class<?> anInterface : interfaces) {
                    classSet.add(anInterface);
                    System.out.println("扫描到注册RPC服务Provider,key:"+key+",value:"+anInterface);
                }
            }
            RpcProviderNode node = RpcProviderNode.build(ip,port,appName,classSet);
            this.registerServerNode(node);
        }
    }

    @Override
    public Class<RpcProviderNode> getServerNodeClass() {
        return RpcProviderNode.class;
    }

    public List<RpcProviderNode> getAllRpcProviderNode(){
        List<String> nodeChild = ZkNodeUtil.getNodeChild(currentNamespace);
        List<RpcProviderNode> result = new ArrayList<>();
        for (String nodePath : nodeChild) {
            String nodeData = ZkNodeUtil.getNodeData(currentNamespace + "/" + nodePath);
            RpcProviderNode node = (RpcProviderNode)JSON.parseObject(nodeData, RpcProviderNode.class);
            result.add(node);
        }
        return result;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

}
